<script setup lang="ts">
import type { UploadProgressEvent } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import type { UploadProps } from 'element-plus'

// defineProps(['modelValue'])
const props = defineProps({
  modelValue: {
    type: String,
    default: ''
  }
})
// defineEmits(['update:modelValue'])
const emits = defineEmits<{
  // (e: 'update:modelValue', value: string): void  // 老板本
  'update:modelValue': [value: string] // vue3.3 新方式 改进
}>()
const imageUrl = ref('') // 直接赋值给 props.modelValue 也会丢失响应性
// imageUrl.value = props.modelValue // 会丢失响应性
watchEffect(() => {
  imageUrl.value = props.modelValue
})
const handleAvatarSuccess: UploadProps['onSuccess'] = (response, uploadFile) => {
  // 创建转化文件本地内存地址，给本地显示
  imageUrl.value = URL.createObjectURL(uploadFile.raw!)
  //   course.value.courseListImg = response.data.name
  emits('update:modelValue', response.data.name)
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('Avatar picture must be JPG format!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('Avatar picture size can not exceed 2MB!')
    return false
  }
  return true
}
// 上传进度
const percentage = ref(0)
// 文件上传回调
const handleProgress = (evt: UploadProgressEvent) => {
  percentage.value = Math.floor(evt.percent)
}
</script>

<template>
  <el-progress type="dashboard" :percentage="percentage" :width="178" v-show="percentage > 0 && percentage < 100" />
  <el-upload
    class="avatar-uploader"
    action="/boss/course/upload"
    :show-file-list="false"
    :on-success="handleAvatarSuccess"
    :before-upload="beforeAvatarUpload"
    :on-progress="handleProgress"
    v-show="percentage === 100 || percentage === 0"
  >
    <img v-if="imageUrl" :src="imageUrl" class="avatar" />
    <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
  </el-upload>
</template>

<style lang="scss" scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
